<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
    </theme-navbar>
    <!-- #endif -->

    <view class="content u-page" style="padding-bottom: 140rpx">
      <view class="card" style="display: flex; align-items: center">
        <view style="font-size: 30rpx; font-weight: 600; margin-right: 16rpx">
          任务紧急程度
        </view>

        <view style="margin: 15rpx 0">
          <u-tag
            v-for="item of urgentStatusList"
            :text="item.text"
            :key="item.value"
            style="margin-right: 20rpx; padding: 12rpx 35rpx; font-size: 28rpx"
            :mode="selectedUrgent == item.value ? 'dark' : 'plain'"
            @click="handleUrgentStatusClick(item)"
          ></u-tag>
        </view>
      </view>

      <view class="card">
        <u-tabs
          :list="businessTabList"
          :is-scroll="false"
          :current="tabCurrent"
          @change="handleTabChange"
        ></u-tabs>
      </view>

      <view class="card">
        <view
          class="group-tag"
          v-for="(item, index) of coordTypeList"
          :key="index"
        >
          <view class="group-name">{{ item.coordTypeName }}</view>
          <view class="group-tag-list">
            <u-tag
              v-for="tagItem of item.tags"
              :text="tagItem.text"
              :key="tagItem.value"
              style="
                margin: 0 20rpx 20rpx 0;
                padding: 18rpx 22rpx;
                font-size: 28rpx;
              "
              :mode="
                selectedTags.indexOf(tagItem.value) > -1 ? 'dark' : 'plain'
              "
              @click="handleTagClick(tagItem)"
            />
          </view>
        </view>
      </view>

      <view class="card" style="padding-top: 25rpx; padding-bottom: 25rpx">
        <u-form labelPosition="top" :model="formData" ref="uForm">
          <u-form-item label="反馈时间" prop="feedbackTime" borderBottom>
            <u-input
              placeholder="请选择"
              v-model="formData.feedbackTime"
              disabled
              @click="handleFeedbackTimeClick"
            />
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="反馈地点" prop="feedbackPlace" borderBottom>
            <u-input placeholder="请填写" v-model="formData.feedbackPlace" />
          </u-form-item>
          <u-form-item label="具体位置" prop="location" borderBottom>
            <u-input placeholder="请选择" v-model="formData.location" disabled @click="handlePlaceClick" />
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="备注说明" prop="taskNote" label-position="top">
            <u-input type="textarea" v-model="formData.taskNote" />
          </u-form-item>
        </u-form>
        <view>
          <upload-images
            :url="uploadFile"
            :length="10"
            :extForm="{
              fiGroupCode: $FILE_GROUP_TYPE.grid_fusio_task_img,
              bizId: formData.taskUuid,
            }"
            :bizId="formData.taskUuid"
            :del-url="delUrl"
            :can-add="true"
            :can-del="true"
            :renderImages="renderImages"
            ref="saveModel3"
            style="padding-left: 0"
          ></upload-images>
        </view>
      </view>
    </view>

    <u-picker v-if="timePickerShow" mode="time" v-model="timePickerShow" :params="timeParams" @confirm="handleTimePickerConfirm"></u-picker>

    <!-- 底部按钮 -->
    <view class="submit-btns btn-other-cls">
      <u-button class="u-btn" @click="handleSaveBtn">保存</u-button>
      <u-button class="u-btn" type="primary" @click="handleSubmitBtn">
        提交
      </u-button>
    </view>
  </view>
</template>

<script>
import commonService from "@/service/eCigar/common.service";
import tripleNetworkIntegrationService from "@/service/tripleNetworkIntegration/tripleNetworkIntegration.service.js";
import { UploadImages } from "@/components";

export default {
  components: {
    UploadImages,
  },
  data() {
    return {
      formData: {
        taskUuid: "",
        location: ""
      },
      uploadFile: commonService.uploadFile,
      delUrl: commonService.deleteFile,
      urgentStatusList: [
        { text: "一般", value: "01" },
        { text: "紧急", value: "02" },
        { text: "特急", value: "03" },
      ],
      selectedUrgent: "", // 任务紧急状态
      swipeOptions: [
        {
          text: "删除",
          style: {
            backgroundColor: "#dd524d",
          },
        },
      ],
      allBusinessList: [], // 所有业务指标
      businessTabList: [],
      tabCurrent: 0,
      selectedTags: [],
      actionType: "", // 操作类型
      timePickerShow: false,
      timeParams: {
				year: true,
				month: true,
				day: true,
				hour: true,
				minute: true,
				second: true
			},
    };
  },
  computed: {
    coordTypeList() {
      let currCoordTypeList = [];
      if (this.allBusinessList.length) {
        currCoordTypeList = this.allBusinessList[this.tabCurrent].coordTypeList;

        currCoordTypeList.map((item) => {
          item.tags = item.coordItemList.map((coordItem) => {
            return { text: coordItem.itemName, value: coordItem.itemUuid };
          });
        });
      }

      return currCoordTypeList;
    },
  },
  onLoad(options) {
    let routeParams = this.getRouteParam();

    if (options.taskUuid) {
      this.formData.taskUuid = options.taskUuid;
    } else if (routeParams.taskUuid) {
      this.formData.taskUuid = routeParams.taskUuid;
    }

    this.initData(this.formData.taskUuid);
  },
  methods: {
    initData(taskUuid) {
      this.$modal.showLoading("加载中...");
      Promise.all([
        tripleNetworkIntegrationService.getGridFusionTaskTaskInfo({ taskUuid }),
        tripleNetworkIntegrationService.getGridFusionTaskItem({ taskUuid }),
      ])
        .then(([res1, res2]) => {
          this.$modal.hideLoading();

          if (res1.success) {
            if (!taskUuid) {
              this.formData = { ...res1.bean };
            } else {
              // 详情
              const {
                task: { taskUrgencyLevel, itemUuidArray },
              } = res1.bean;
              this.selectedUrgent = taskUrgencyLevel; // 任务紧急状态
              this.selectedTags = itemUuidArray;
              this.formData = { ...res1.bean.task };
            }
          } else {
            this.$u.toast(res1.msg);
          }

          // 所有指标类型
          if (res2.success) {
            this.allBusinessList = res2.data;
            this.businessTabList = res2.data.map((item) => {
              return { name: item.businessName };
            });

            let tabCurrent = this.allBusinessList.findIndex(
              (item) => item.businessType === this.formData.businessType
            );
            this.tabCurrent = tabCurrent > -1 ? tabCurrent : 0;
          } else {
            this.$u.toast(res2.msg);
          }
        })
        .catch(() => {
          this.$u.toast("数据获取失败!");
          this.$modal.hideLoading();
        });
    },
    handleUrgentStatusClick(data) {
      this.selectedUrgent = data.value;
    },
    handleTabChange(e) {
      this.tabCurrent = e;
      this.selectedTags = []; // 清空选中的标签
    },
    handleTagClick(data) {
      if (this.selectedTags.indexOf(data.value) > -1) {
        this.selectedTags = this.selectedTags.filter(
          (item) => item != data.value
        );
      } else {
        this.selectedTags.push(data.value);
      }
    },
    updateBackState(param) {
      if (param["flowUserSelectBack"]) {
        // 审核人员选择回调
        this.nextPersonUuids = param["flowUserSelectBack"]
          .map((item) => item.personId)
          .join(",");
        let paras = this.validatePageData();
        this.saveGridFusionTask(paras);
      } else if (param.pos) {
        this.formData = { ...this.formData, location: param.pos.detailAddress };
      }
    },
    renderImages() {
      return new Promise((res, rej) => {
        commonService
          .findFilesByBizId(
            this.$FILE_GROUP_TYPE.grid_fusio_task_img,
            this.formData.taskUuid
          )
          .then((r) => {
            if (r.code == 200 && r.success && Array.isArray(r.data)) {
              r.data.forEach((i) => {
                i.src = `${
                  commonService.baseUrl
                }/commonfile/filestore/downloadFile.do?fileId=${
                  i.gfiId
                }&tk=${uni.getStorageSync("tk")}`;
                i.filePath = i.src;
              });
              res(r.data);
            } else {
              res([]);
            }
          });
      });
    },
    handleFeedbackTimeClick() {
      this.timePickerShow = true;
    },
    handleTimePickerConfirm(e) {
      this.formData.feedbackTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:${e.second}`;
    },
    handlePlaceClick() {
      this.setRouteParam({ disable: false, step: "start" });
      this.$u.route("pages/commonPage/modifyLocationMap");
    },
    validatePageData() {
      if (!this.selectedUrgent) {
        this.$u.toast("请选择任务紧急程度!");
        return;
      } else if (!this.selectedTags.length) {
        this.$u.toast("请选择问题类型!");
        return;
      } else if (!this.formData.feedbackTime) {
        this.$u.toast("请选择反馈时间!");
      } else if (!this.formData.feedbackPlace) {
        this.$u.toast("请选择反馈地点!");
      } else {
        let paras = {
          ...this.formData,
          businessType: this.allBusinessList[this.tabCurrent].businessType, // 指标大类
          taskUrgencyLevel: this.selectedUrgent, // 任务紧急状态
          checkedItemList: this.selectedTags, // 协同问题集合
          nextPersonUuids: this.nextPersonUuids, // 下一步审核人uuid
        };
        return paras;
      }
    },
    handleSaveBtn() {
      this.actionType = "save";
      let paras = this.validatePageData();
      if (!paras) {
        return;
      }
      this.saveGridFusionTask(paras);
    },
    saveGridFusionTask(paras) {
      this.$modal.showLoading("数据保存中...");
      let actionTypeMsg = this.actionType === "save" ? "保存" : "提交";

      tripleNetworkIntegrationService
        .saveGridFusionTask(paras)
        .then((res) => {
          this.$modal.hideLoading();
          if (res.success) {
            this.$u.toast(actionTypeMsg + "成功!");
            setTimeout(() => {
              this.backPrev({
                paramKey: "submitSuccess",
                param: true,
              });
            }, 1000);
          } else {
            this.$u.toast(res.msg);
          }
        })
        .catch(() => {
          this.$u.toast(actionTypeMsg + "失败!");
          this.$modal.hideLoading();
        });
    },
    // 获取流程获选人参数
    getNextFlowUsersExtData() {
      this.$modal.showLoading("获取候选人中...");
      tripleNetworkIntegrationService
        .getNextFlowUsersExtData({
          taskUuid: this.formData.taskUuid,
          businessType: this.allBusinessList[this.tabCurrent].businessType,
        })
        .then((res) => {
          if (res.success) {
            let flowCode = "gridFusionTask";
            let extParams = res.bean || {};
            this.setRouteParam({
              ...extParams,
            });
            this.$u.route({
              url: "/pages/commonPage/flowUserSelectComponent",
              params: {
                flowFormCode: flowCode,
                // docInsUuid: this.formData.taskUuid
              },
            });
          } else {
            this.$u.toast(res.msg);
          }
        })
        .catch(() => {
          this.$u.toast("候选人获取失败!");
        });
    },
    handleSubmitBtn() {
      this.actionType = "submit";
      let valid = this.validatePageData();
      if (!valid) {
        return;
      }
      this.getNextFlowUsersExtData();
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 0;
}
.content {
  background-color: #f3f4f5;
}

.card {
  margin-left: 0;
  margin-right: 0;
  border-radius: 0;
  padding-left: 25rpx;
  padding-right: 25rpx;
}

.group-tag {
  .group-name {
    font-size: 30rpx;
    font-weight: 600;
    margin: 20rpx 0 18rpx;
  }
}
</style>